package common

import (
	"context"
	"log"
	"time"
)
func init()  {
	log.SetFlags(log.Lshortfile|log.Lmicroseconds)
}
type BatchLog struct {
	logChan     chan *JobLog
	logManyChan chan *ManyLogs
	size        int
}

var (
	GBatchLog *BatchLog
)

func (bl *BatchLog) write() {
	var (
		many  *ManyLogs
		timer *time.Timer
	)
	for {
		select {
		case tlog := <-bl.logChan:
			if many == nil {
				many = &ManyLogs{}
				//如果日志太少，不到size，则1s提交一次
				timer = time.AfterFunc(time.Second, func(my *ManyLogs) func() {
					return func() { //这个方法在新的携程中启动，所以参数必须这么传
						bl.logManyChan <- many
					}
				}(many))
			}

			many.Logs = append(many.Logs, tlog)
			if len(many.Logs) >= bl.size {
				bl.Save(many)
				many = nil

				timer.Stop()//如果这里提交过，就关闭timer，避免重复提交
			}
		case mlogs := <-bl.logManyChan:
			if mlogs != many { //说明已经save过了
				continue
			}
			bl.Save(mlogs)
			many = nil
		}
	}

}

func (bl *BatchLog) AddLog(log *JobLog) {
	bl.logChan <- log
}
func (bl *BatchLog) Save(many *ManyLogs) {
	ret, err := GMongo.Collection.InsertMany(context.TODO(), many.Logs)

	if err != nil {
		Warn(nil, err, ret)
	}
}
func InitBatchLog() (err error) {
	GBatchLog = &BatchLog{
		logChan: make(chan *JobLog, 1024),
		logManyChan:make(chan *ManyLogs,1024),
		size:    10,
	}
	go GBatchLog.write()
	return
}
